package com.pubinfo.passbook.reference.impl;

import cn.com.bonc.service.esb.EsbService;
import com.alibaba.fastjson.JSONObject;
import com.pubinfo.passbook.common.model.dubbo.ESBServiceData;
import com.pubinfo.passbook.common.utils.AESUtil;
import com.pubinfo.passbook.reference.ESBServiceReference;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * 人力服务接口
 *
 * @author zhouch
 * @date 2021/11/18 16:55
 */
@Service
@Slf4j
public class ESBServiceReferenceImpl implements ESBServiceReference {
  
  @Resource
  EsbService esbService;
  
  @Value("${esb.security-key.aes}")
  private String aesKey;
  
  @Value("${esb.sys-id}")
  private String sysId;
  
  @Value("${esb.service}")
  private String serviceName;
  
  @Value("${esb.security-key.sign}")
  private String signKey;
  
  private static AESUtil.AESEncrytor encryptor;
  
  /**
   * 获取身份详情
   *
   * @param cert
   * @return
   */
  @Override
  public Collection<ESBServiceData.CertDetail> getPersonsDetail(ESBServiceData.Cert cert) {
    // 初始化加密器
    initAESEncryptor();
    List<ESBServiceData.Cert> certs = new ArrayList<>();
    // 组装参数
    certs.add(cert);
    ESBServiceData.In param = ESBServiceData.In.makeInstance(certs, signKey, sysId, serviceName);
    
    if (log.isDebugEnabled()) {
      log.debug("发送报文: {}", param.toJson());
    }
    
    // 加密
    String reqStrEnc = encryptor.encrypt(param.toJson());
    
    // 调用，返回加密后的响应
    String resultEnc = esbService.handle(reqStrEnc);
    
    // 解密
    String resultJson = encryptor.decrypt(resultEnc);
    
    if (log.isDebugEnabled()) {
      log.debug("响应报文: {}", resultJson);
    }
    
    // 序列化成对象
    ESBServiceData.Out result = JSONObject.parseObject(resultJson, ESBServiceData.Out.class);
    
    return result.getData();
  }
  
  private void initAESEncryptor() {
    if (encryptor == null) {
      synchronized (this) {
        if (encryptor == null && aesKey.length() != 0) {
          encryptor = new AESUtil.AESEncrytor(aesKey);
        }
      
        if (encryptor == null && aesKey.length() == 0) {
          // 通常，不会进入这里
          throw new RuntimeException("尝试在没有AES密钥的情况创建加密对象。");
        }
      }
    }
  }
}
